package com.sgb.kjwl.view.widget;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.sgb.capital.view.widget.MToast;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.databinding.PopwindowMapHallCarBinding;
import com.sgb.kjwl.model.entity.transport.VehicleHallMapEntity;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.LogisticsPermissionHelper;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.utils.VehicleConstant;
import com.sgb.kjwl.view.ui.activity.self.logistics.InquiryActivity;
import com.sgb.kjwl.view.ui.activity.transport.InquireByLetterActvity;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.VehicleDetailActivity;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.PopViewHolder;
import com.swgk.core.dialog.RoundDialog;

import java.math.BigDecimal;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: 杨畔
 * @date: 2021/9/13 14:58
 * @Description: 货车大厅marker弹窗
 */
public class MapHallCarPopWindow extends BasePopWindow<Object> implements View.OnClickListener {
    private PopwindowMapHallCarBinding binding;
    private VehicleHallMapEntity mEntity;
    protected OnClickCallBack onClickCallBack;

    public void setOnClickCallBack(OnClickCallBack onClickCallBack) {
        this.onClickCallBack = onClickCallBack;
    }

    public interface OnClickCallBack {
        void message(String account);
    }

    public MapHallCarPopWindow(Context context) {
        super(context, DIR_DOWN_UP);
    }

    @Override
    protected int popLayout() {
        return R.layout.popwindow_map_hall_car;
    }

    @Override
    protected void initView(PopViewHolder holder) {
        binding = (PopwindowMapHallCarBinding) holder.getmBinding();
        binding.tvMsg.setOnClickListener(this);
        binding.tvTel.setOnClickListener(this);
        binding.tvInquireByLetter.setOnClickListener(this);
        binding.tvInvite.setOnClickListener(this);
        binding.tvBtn.setOnClickListener(this);
        binding.infoLayout.setOnClickListener(this);
    }

    /**
     * 设置数据
     */
    public void setData(VehicleHallMapEntity entity) {
        mEntity = entity;
        if (mEntity == null) return;
        Glide.with(mContext).load(DefaultUtil.getString(entity.getCarImage()))
                .error(R.mipmap.ic_default_car)
                .placeholder(R.mipmap.ic_default_car)
                .transform(new CenterCrop(), new RoundedCorners(10))
                .into(binding.ivCarImage);
        binding.tvNumber.setText(String.format("%s", entity.getCarNumber()));
        binding.tvDriver.setText(String.format("%s", entity.getName()));
        if (BigDecimal.ZERO.compareTo(BigDecimal.valueOf(entity.getDistance())) != 0) {
            binding.tvDistance.setText(String.format("%s", entity.getDistance() < 1000
                    ? "距您1km以内"
                    : String.format("%skm", "距您" + NumberUtil.trim0(entity.getDistance() / 1000))));
        }
        binding.tvCarInfo.setText(String.format("%s 车长%s %s吨%s%s",
                entity.getCarTypeName(),
                entity.getCarLenName(),
                NumberUtil.trim0(entity.getWeight()),
                TextUtils.isEmpty(entity.getHeightHurdle())
                        ? ""
                        : String.format(" %s米", entity.getHeightHurdle()),
                entity.getIsDumper() == null
                        ? ""
                        : String.format(" %s", VehicleConstant.getIsDumpStr(entity.getIsDumper()))));
        //无im信息置灰消息按钮
        if (TextUtils.isEmpty(entity.getDriverCreateIm())) {
            binding.tvMsg.setAlpha(0.5f);
            binding.tvMsg.setEnabled(false);
        } else {
            binding.tvMsg.setAlpha(1f);
            binding.tvMsg.setEnabled(true);
        }
        //无手机号信息置灰联系按钮
        if (TextUtils.isEmpty(entity.getTelphone())) {
            binding.tvTel.setAlpha(0.5f);
            binding.tvTel.setEnabled(false);
        } else {
            binding.tvTel.setAlpha(1f);
            binding.tvTel.setEnabled(true);
        }
        resetImMsg(entity);

        RequestOptions requestOptions = null;
        if (entity.getTerminal() == 1) {
            requestOptions = new RequestOptions()
                    .placeholder(R.mipmap.icon_company_default)//图片加载出来前，显示的图片
                    .fallback(R.mipmap.icon_company_default) //url为空的时候,显示的图片
                    .error(R.mipmap.icon_company_default);//图片加载失败后，显示的图片
        } else if (entity.getTerminal() == 2) {
            requestOptions = new RequestOptions()
                    .placeholder(R.mipmap.icon_team_default_1)//图片加载出来前，显示的图片
                    .fallback(R.mipmap.icon_team_default_1) //url为空的时候,显示的图片
                    .error(R.mipmap.icon_team_default_1);//图片加载失败后，显示的图片
        } else if (entity.getTerminal() == 3) {
            requestOptions = new RequestOptions()
                    .placeholder(R.drawable.geren_person_touxiang)//图片加载出来前，显示的图片
                    .fallback(R.drawable.geren_person_touxiang) //url为空的时候,显示的图片
                    .error(R.drawable.geren_person_touxiang);//图片加载失败后，显示的图片
        }

        if (TextUtils.isEmpty(entity.getRoleName())) {
            binding.info.setVisibility(View.GONE);
        } else {
            binding.info.setVisibility(View.VISIBLE);
            binding.teamName.setText(entity.getRoleName());
            Glide.with(mContext).load(entity.getImg()).apply(requestOptions).into(binding.teamImg);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_msg:
                //检查登录状态
                if (UserOperating.getInstance().isNotLogged(mContext)) {
                    return;
                }
                if(mEntity!=null&&!UserOperating.getInstance().IsAuth(mContext,mEntity.getAuthTime())){
                    return;
                }
                imClick();
                break;
            case R.id.tv_tel:
                //检查登录状态
                if (UserOperating.getInstance().isNotLogged(mContext)) {
                    return;
                }
                if(mEntity!=null&&!UserOperating.getInstance().IsAuth(mContext,mEntity.getAuthTime())){
                    return;
                }
                telClick();
                break;
            case R.id.tv_invite:
                //判断登录
                if (UserOperating.getInstance().isNotLogged(mContext)) {
                    return;
                }
                if(mEntity!=null&&!UserOperating.getInstance().IsAuth(mContext,mEntity.getAuthTime())){
                    return;
                }
                //邀请
                LogisticsPermissionHelper.getInstance().checkPermissionToInvite(mContext, "", 0);
                break;
            case R.id.tv_inquire_by_letter:
                if (UserOperating.getInstance().isNotLogged(mContext)) {
                    return;
                }
                if(mEntity!=null&&!UserOperating.getInstance().IsAuth(mContext,mEntity.getAuthTime())){
                    return;
                }
                //函询
                inquireByLetter();
                break;
            case R.id.tv_btn:
                if(mEntity!=null&&!UserOperating.getInstance().IsAuth(mContext,mEntity.getAuthTime())){
                    return;
                }
                inquiryClick();
                break;
            case R.id.info_layout:
                infoLayoutClick();
                break;

        }
    }

    private void imClick() {
        if ( !TextUtils.isEmpty(mEntity.getDriverCreateIm())) {
            if (onClickCallBack != null) {
                onClickCallBack.message(mEntity.getDriverCreateIm());
            }
            //清除消息提醒
            if (onResultCallBack != null) {
                //TODO 设置消息红点
//                onResultCallBack.result(mEntity.getImContact());
            }
            resetImMsg(mEntity);
        }
    }

    private void telClick() {
        if (mEntity != null && !TextUtils.isEmpty(mEntity.getTelphone())) {
            showTelDialog(mEntity.getTelphone());
        }
    }

    private void inquireByLetter() {
        //函询
        InquireByLetterActvity.start(mContext, 2,
                mEntity.getName(), mEntity.getUserNo(),
                mEntity.getDriverAuthNo(), mEntity.getCarNumber());
    }

    private void inquiryClick() {
        if (UserOperating.getInstance().isNotOpenFundAccount(mContext, PermissionCheckUtil.KEY_WODEXUNJIA)) {
            return;
        }
        NewAPIManager.getInstance().getLogisticsAPI().getInquiryPermissions(mEntity.getNo(), "").enqueue(new ICallBack<BaseEntity<Boolean>>() {

            @Override
            public void onSuccess(BaseEntity<Boolean> data) {
                if(data.isSuccess()){
                    if (data.getData()) {
                        if (mEntity != null) {
                            //询价填写资料页
                            InquiryActivity.startCarInquiry(mContext, DefaultUtil.getString(mEntity.getNo()), mEntity.getTelphone());
                            //清除消息提醒
                            if (onResultCallBack != null) {
                                //TODO 设置消息红点
//            onResultCallBack.result(mEntity.getImContact());
                            }
                        }
                    } else {
                        MToast.showToast(mContext, "不能对自己发布的车辆进行询价！");
                    }
                }
            }
        });
    }

    private void infoLayoutClick() {
        VehicleDetailActivity.start(mContext, mEntity.getNo());
    }

    /**
     * 设置im消息红点
     */
    private void resetImMsg(VehicleHallMapEntity entity) {
        //TODO 设置消息红点
//        if (entity.getImContact() != null && entity.getImContact().getUnreadCount() > 0) {
//            binding.tvMsgBadge.setText(entity.getImContact().getUnreadCount() > 99
//                    ? "99+"
//                    : String.valueOf(entity.getImContact().getUnreadCount()));
//            binding.tvMsgBadge.setVisibility(View.VISIBLE);
//        } else {
//            binding.tvMsgBadge.setVisibility(View.GONE);
//        }
    }

    private void showTelDialog(String phone) {
        new RoundDialog.Builder(mContext)
                .title("是否拨打电话")
                .content(phone)
                .confirm("拨打")
                .cancelable(false)
                .confirmCallback(v -> {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    mContext.startActivity(intent);
                })
                .show();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        clearAlpha();
    }
}
